package cn.thoughtworks.school.programCenter.services;

import cn.thoughtworks.school.programCenter.entities.Group;
import cn.thoughtworks.school.programCenter.entities.Tag;
import cn.thoughtworks.school.programCenter.entities.UserGroup;
import cn.thoughtworks.school.programCenter.entities.UserGroup;
import cn.thoughtworks.school.programCenter.entities.vo.StudentTag;
import cn.thoughtworks.school.programCenter.repositories.GroupRepository;
import cn.thoughtworks.school.programCenter.repositories.UserGroupRepository;
import cn.thoughtworks.school.programCenter.repositories.UserTagRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserGroupService {
    @Autowired
    private GroupRepository groupRepository;
    @Autowired
    private UserGroupRepository userGroupRepository;

    @Transactional
    public void editTags(Long programId, Long studentId, Long operatorId, List<String> groups) {
        List<UserGroup> userGroups = userGroupRepository.findByProgramIdAndStudentId(programId, studentId);
        List<String> tagsName = userGroups.stream().map(item -> item.getGroup().getName())
                .collect(Collectors.toList());

        List<String> shouldAdd = groups.stream().filter(item -> !tagsName.contains(item)).collect(Collectors.toList());
        List<UserGroup> shouldDelete = userGroups.stream().filter(item -> !groups.contains(item.getGroup().getName()))
                .collect(Collectors.toList());

        userGroupRepository.deleteAll(shouldDelete);
        userGroupRepository.saveAll(
                shouldAdd.stream().map(item -> {
                    Group group = groupRepository.findByName(item).findFirst()
                            .orElse(new Group(item, new Date(), operatorId));
                    return new UserGroup(studentId, new Date(), operatorId, group, programId);
                }).collect(Collectors.toList())
        );
    }
}
